package com.itheima.dfs.controller;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.common.constants.BusinessConstants;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.RequestContextUtil;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.feign.WmMaterialFeign;
import com.itheima.wemedia.pojo.WmMaterial;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/dfs")
@Slf4j
public class FileController {

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer WebServer;

    @Autowired
    private WmMaterialFeign wmMaterialFeign;


    @PostMapping("/upload")
    public ResultVo upload(MultipartFile multipartFile){
        //获得请求的来源(来自请求头中)，并对来源进行非空判断
        String headerFrom = RequestContextUtil.getHeader(SystemConstants.USER_HEADER_FROM);
        if (StringUtils.isEmpty(headerFrom)){
            return ResultVo.bizError("非法的请求,拒绝上传素材");
        }

        try {
            StorePath storePath = client.uploadFile(multipartFile.getInputStream(),
                    multipartFile.getSize(),
                    StringUtils.getFilenameExtension(multipartFile.getOriginalFilename()),
                    null);
            //拼接得到完整的图片地址 WebServer.getWebServerUrl() ----> http:192.168.136.128/
            //storePath.getFullPath()  ----> group1/M00/00/00/wKjTiF_BIUqAMwDrAAAl8vdCW2Y127.png
            //拼接后：http:192.168.136.128/group1/M00/00/00/wKjTiF_BIUqAMwDrAAAl8vdCW2Y127.png
            String url =WebServer.getWebServerUrl()+storePath.getFullPath();
            log.info("文件上传成功的url：{}",url);

            //获得文件的id
            String fileId = storePath.getFullPath();
            //如果有来源，且来源正确 ，就调用自媒体微服务添加素材
            if("wemedia-pic".equals(headerFrom)){
                addWmMaterial(fileId);
            }

            Map<String, String> map = new HashMap<>();
            map.put("url",url);
            return ResultVo.ok(map);

        } catch (IOException e) {
           log.error("文件上传失败了："+e);
        }
       return ResultVo.error();

    }

    private void addWmMaterial(String fileId) {
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(RequestContextUtil.getUserId());
        wmMaterial.setUrl(fileId);
        wmMaterial.setType(BusinessConstants.WmMaterial.TYPE_PICTURE); //0表示是图片
        wmMaterial.setIsCollection(BusinessConstants.WmMaterial.NOT_IS_COLLECTION); //0表示未收藏
        wmMaterial.setCreatedTime(LocalDateTime.now());
        //调用自媒体微服务添加素材
        ResultVo<WmMaterial> resultVo = wmMaterialFeign.add(wmMaterial);
        if (!resultVo.isSuccess()){
           throw new LeadNewsException("远程调用自媒体微服务添加素材失败了");
        }

    }






}
